#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDesktopWidget>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //设置窗口位置
    this->move(QApplication::desktop()->width()-120,QApplication::desktop()->height()-80);
    this->setWindowFlags(Qt::FramelessWindowHint //去边框
               |Qt::WindowStaysOnTopHint //最低层显示
               |Qt::Tool //不在任务栏显示
             );
    this->setAttribute(Qt::WA_TranslucentBackground, true);
    setSystemTray();
    process = new QProcess(this);
    timer = new QTimer(this);
    timer->connect(timer, SIGNAL(timeout()), this, SLOT(GetInformation()));
    timer->start(1000);
    oldMousePos.setX(0);
    oldMousePos.setY(0);
}

void MainWindow::mousePressEvent(QMouseEvent *event){
    if(!isMousePressed && event->button() == Qt::LeftButton){
        isMousePressed = true;
        oldMousePos = event->globalPos() - this->pos();
        this->setCursor(Qt::ClosedHandCursor);
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event){
    if(isMousePressed){
        this->move(event->globalPos() - oldMousePos);
        event->accept();
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event){
    if(isMousePressed && event->button() == Qt::LeftButton){
        int x=this->x();
        int y=this->y();
        if(this->pos().x()<0){
            x=0;
        }else if(QApplication::desktop()->width()-x<this->width()){
            x=QApplication::desktop()->width()-this->width();
        }
        if(this->pos().y()<0) {
            y=0;
        }else if(QApplication::desktop()->height()-y<this->height()){
            y=QApplication::desktop()->height()-this->height();
        }
        move(x,y);

        isMousePressed=false;
        setCursor(Qt::ArrowCursor);
        event->accept();
    }
}

void MainWindow::paintEvent(QPaintEvent *){

}

void MainWindow::OnTrayContextMenuClick(QAction*){
    timer->stop();
    QApplication::exit();
}

void MainWindow::GetInformation(){
    timer->stop();
    GetNetInformation();
    GetFreeMemoryInfo();
    timer->start(1000);
}

void MainWindow::GetNetInformation(){
    uploadCount = 0;
    downloadCount = 0;
    process->start("ip -s link");
    if(process->waitForStarted(2000) && process->waitForFinished(1000)){
        QByteArray infoBytes = process->readAllStandardOutput();
        if(!infoBytes.isEmpty()){
            QString infoResult(infoBytes);
            //计算上传
            QRegularExpression regExpress("collsns[\\s\\S]+?\\d+");
            QRegularExpressionMatchIterator matcherIter = regExpress.globalMatch(infoResult);
            while(matcherIter.hasNext()){
                QString net = matcherIter.next().captured(0);
                net.remove(QRegularExpression("[\\s\\S]+ "));
                uploadCount += net.toInt();
            }
            qint64 tmp = uploadCount - oldUploadCount;
            if(oldUploadCount != 0)
                ui->lbUpload->setText("↑  " + GetSizeInfo(tmp));
            oldUploadCount = uploadCount;
            //计算下载
            regExpress.setPattern("mcast[\\s\\S]+?\\d+");
            matcherIter = regExpress.globalMatch(infoResult);
            while(matcherIter.hasNext()){
                QString net = matcherIter.next().captured(0);
                net.remove(QRegularExpression("[\\s\\S]+ "));
                downloadCount += net.toLongLong();
            }
            tmp = downloadCount - oldDownloadCount;
            if(oldDownloadCount != 0)
                ui->lbDownload->setText("↓  " + GetSizeInfo(tmp));
            oldDownloadCount = downloadCount;
        }
    }
}

void MainWindow::GetFreeMemoryInfo(){
    process->start("free -m");
    if(process->waitForStarted(2000) && process->waitForFinished(1000)){
        QByteArray infoResult = process->readAllStandardOutput();
        if(!infoResult.isEmpty()){
            QRegularExpression regExpress("\\d+.+");
            QString value = regExpress.match(infoResult).captured(0);
            QStringList infoList = value.split(QRegExp(" +"));
            QString totalStr = infoList.at(0), availableStr = infoList.at(5);
            qint64 totalCount = totalStr.toLongLong(),
                   availableCount = availableStr.toLongLong();
            qint64 used = totalCount - availableCount;
            int usedPercent = (int)(used * 100.0 / totalCount);
            ui->pbMemory->setValue(usedPercent);
        }
    }
}

QString MainWindow::GetSizeInfo(qint64 value){
    if(value >= 1024*1024){
        return QString().setNum(value/1024/1024) + "m/s";
    }else if(value >= 1024){
        return QString().setNum(value/1024)+"k/s";
    }else{
        return QString().setNum(value)+"b/s";
    }
}

void MainWindow::setSystemTray(){
    trayIcon = new QSystemTrayIcon(QIcon(":/icon.png"), this);
    trayIcon->setToolTip("流量监控悬浮框");
    QMenu *exitMenuItem = new QMenu();
    QAction *exitAction = new QAction("退出应用");
    exitMenuItem->addAction(exitAction);
    connect(exitMenuItem, SIGNAL(triggered(QAction*)), SLOT(OnTrayContextMenuClick(QAction*)));
    trayIcon->setContextMenu(exitMenuItem);
    trayIcon->show();
}

MainWindow::~MainWindow()
{
    delete ui;
}
